#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define THREADNUM 4

int g_val = 100;

//无锁数据异常案例
void* buyTicket(void* arg)
{
    while (1)
    {
        if (g_val > 0)
        {
            printf("%p:have ticket %d\n", pthread_self(), g_val);
            g_val--;
        }
        else
        {
            break;
        }
    }

    return NULL;
}

int main()
{
    pthread_t tid[THREADNUM];
    for (int i = 0; i < THREADNUM; i++)
    {
        int ret = pthread_create(&tid[i], NULL, buyTicket, NULL);
        if (ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
    }

    for (int i = 0; i < THREADNUM; i++)
    {
        pthread_join(tid[i], NULL);
    }

    return 0;
}